<%@ page contentType="text/html;charset=UTF-8"%>
<jsp:include page="head.jsp"></jsp:include>
 <script> 
    function test(){
    var meta = [
        {header:'编号',dataIndex:'id', name: 'id'},
        {header:'名称',dataIndex:'name', name: 'name'},
        {header:'描述',dataIndex:'descn', name: 'descn'},
        {header:'日期',dataIndex:'date', name: 'date', type: 'date', dateFormat: 'Y-m-dTH:i:s', renderer: Ext.util.Format.dateRenderer('Y-m-d')}
    ];

    var data = [
        ['1','name1','descn1','1970-01-15T02:58:04'],
        ['2','name2','descn2','1970-01-15T02:58:04'],
        ['3','name3','descn3','1970-01-15T02:58:04'],
        ['4','name4','descn4','1970-01-15T02:58:04'],
        ['5','name5','descn5','1970-01-15T02:58:04']
    ];

    var grid = new Ext.grid.GridPanel({
        height: 380,
        width: 450,
  		renderTo: Ext.getBody(),
        enableDragDrop: true,
        title: '通过拖拽Grid改变行的顺序',
        frame: true,
        enableDrag: true,
        store: new Ext.data.Store({
            autoLoad: true,
            proxy: new Ext.data.MemoryProxy(data),
            reader: new Ext.data.ArrayReader({}, meta)
        }),
        columns: meta,
        viewConfig: {
            columnsText: '显示的列',
            scrollOffset: 30,
            sortAscText: '升序',
            sortDescText: '升序',
            forceFit: true
        },  
        stripeRows: true,
            autoExpandColumn: 1,
            tbar: [{
                text: '上移',
                iconCls: 'up',
                scope: this,
                handler: function(){
                    buttonMove(-1);
                }
            }, {
                text: '下移',
                iconCls: 'down',
                scope: this,
                handler: function(){
                    buttonMove(1);
                }
            }, '-', {
                text: '保存',
                iconCls: 'save',
                scope: this,
                handler: function(){
                    var ds = grid.getStore();
                    var sortIndex = [];
                    for (var i = 0; i < ds.getCount(); i++) {
                        sortIndex.push(ds.data.items[i].id);
                    }
                    Ext.fly('op').dom.value += '------------\n' + sortIndex + '\n';
                    Ext.Ajax.request({
                        url: 'gridDD_sort.ashx?act=save',
                        params: {
                            sortIndex: sortIndex
                        },
                        success: function(response, op){
                            var msg = response.responseText;
                            var obj = Ext.decode(msg);
                            if (obj) {
                                msg = obj.success?"新的行顺序已保存！":obj.data;
                            }
                            Ext.Msg.alert('信息', msg);
                        },
                        failure: function(response, op){
                            Ext.Msg.alert('信息', response.responseText);
                        }
                    });
                }
            }]
        });
                
        function buttonMove(toward){
            var sm = grid.getSelectionModel();
            var data = sm.getSelections();
            if (sm.hasSelection()) {
                //获取选择行第1行
                var rec = sm.getSelected();
                var ds = grid.getStore();
                //默认的插入行
                var rowIndex = ds.indexOfId(rec.id) + toward;
                //判断插入是否已选择，如果已选择，重新获取插入行
                var ri = []; //插入行的行号数组
                for (var i = 1; i < data.length; i++) {
                    var index = ds.indexOfId(data[i].id)
                    ri.push(index);
                }
                //对插入行数组进行排序，下移顺序排序，上移反序排序
                if (toward == 1) {
                    ri.sort(function(x, y){
                        if (parseInt(x) > parseInt(y)) 
                            return 1
                        else 
                            return -1
                    })
                }
                else {
                    ri.sort(function(x, y){
                        if (parseInt(x) > parseInt(y)) 
                            return -1
                        else 
                            return 1
                    })
                }
                //如果插入行是选择行，则插入行前移或后移
                for (var i = 0; i < ri.length; i++) {
                    if (rowIndex == ri[i]) 
                        rowIndex += toward;
                }
                //判断插入行是否已在顶部或底部，不是则执行移动操作
                if (rowIndex < 0) {
                    Ext.Msg.alert('信息', '记录已在顶部');
                }
                else 
                    if (rowIndex >= ds.getCount()) {
                        Ext.Msg.alert('信息', '记录已在底部');
                    }
                    else {
                        move(rowIndex, data);
                    }
            }
            else {
                Ext.Msg.alert('信息', '请选择记录');
            }
        }
                
        function move(rindex, data){
            var ds = grid.getStore(), rdata = ds.getAt(rindex); // 获取插入行的记录
            var toward = 0; // 默认是上移操作
            var index = ds.indexOfId(data[0].id);
            
            if (rindex > index){
                toward = 1 // 如果是下移，修改方向值
            }
                
            // 移除选择行
            for (i = 0; i < data.length; i++) {
                ds.remove(ds.getById(data[i].id));
            }
            // 根据id获取插入行的新位置并根据移动操作计算出插入位置
            rindex = ds.indexOfId(rdata.id) + toward;
            // 从插入位置依次插入选择行
            for (i = 0; i < data.length; i++) {
                ds.insert(rindex, data[i]);
                rindex++;
            }
            
            var sm = grid.getSelectionModel();
            if (sm)sm.selectRecords(data);// 重新选择选择行
        }
        
        new Ext.dd.DropTarget(grid.getEl(), {
            ddGroup: grid.ddGroup || 'GridDD',
            grid: grid,
            gridDropTarget: this,
            notifyDrop: function(dd, e, data){
                
                var t = e.getTarget();// 获取选择行
                var rindex = this.grid.view.findRowIndex(t);
                if (rindex === false) 
                    return false;
                var ds = this.grid.getStore();
                var rdata = ds.getAt(rindex);
                
                // 判断插入行是否选择行，如果是不允许插入
                for (i = 0; i < data.selections.length; i++) {
                    var rowIndex = ds.indexOfId(data.selections[i].id);
                    if (rindex == rowIndex) 
                        rindex = false;
                }
                move(rindex, data.selections)
                return true;
            },
            
            notifyOver: function(dd, e, data){
                var t = e.getTarget();
                var rindex = this.grid.view.findRowIndex(t);
                var ds = this.grid.getStore();
                for (i = 0; i < data.selections.length; i++) {
                    var rowIndex = ds.indexOfId(data.selections[i].id);
                    if (rindex == rowIndex) 
                        rindex = false;
                }
                return (rindex === false) ? this.dropNotAllowed : this.dropAllowed;
            }
        });
   }
    </script>
 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>办公自动化系统</title>
</head>
<body onload="javascript:test();">
</body>
</html>  